<?php
require_once __DIR__ . '/../../functions.php';

header('Content-Type: application/json');

// 检查管理员权限
if (!isAdmin()) {
    echo json_encode(['success' => false, 'message' => '您没有权限执行此操作']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $userId = intval($_POST['user_id'] ?? 0);
    $username = sanitizeInput($_POST['username'] ?? '');
    $phone = sanitizeInput($_POST['phone'] ?? '');
    $group_name = sanitizeInput($_POST['group_name'] ?? '');
    $wechat_account = sanitizeInput($_POST['wechat_account'] ?? '');
    $alipay_account = sanitizeInput($_POST['alipay_account'] ?? '');
    $account_holder = sanitizeInput($_POST['account_holder'] ?? '');
    $bank_name = sanitizeInput($_POST['bank_name'] ?? '');
    $bank_card_number = sanitizeInput($_POST['bank_card_number'] ?? '');
    $wechat_nickname = sanitizeInput($_POST['wechat_nickname'] ?? '');
    $status = isset($_POST['status']) ? 1 : 0;
    $is_admin = isset($_POST['is_admin']) ? 1 : 0;
    
    if ($userId <= 0) {
        echo json_encode(['success' => false, 'message' => '用户ID无效']);
        exit;
    }
    
    if (empty($username) || empty($phone)) {
        echo json_encode(['success' => false, 'message' => '用户名和手机号不能为空']);
        exit;
    }
    
    if (!validatePhone($phone)) {
        echo json_encode(['success' => false, 'message' => '手机号格式不正确']);
        exit;
    }
    
    $db = getDB();
    
    // 检查手机号是否被其他用户使用
    $stmt = $db->prepare("SELECT id FROM users WHERE phone = ? AND id != ?");
    $stmt->execute([$phone, $userId]);
    if ($stmt->fetch()) {
        echo json_encode(['success' => false, 'message' => '该手机号已被其他用户使用']);
        exit;
    }
    
    // 更新用户信息
    $stmt = $db->prepare("UPDATE users SET 
        username = ?, phone = ?, group_name = ?, wechat_account = ?, 
        alipay_account = ?, account_holder = ?, bank_name = ?, 
        bank_card_number = ?, wechat_nickname = ?, status = ?, is_admin = ?
        WHERE id = ?");
    
    if ($stmt->execute([
        $username, $phone, $group_name, $wechat_account, 
        $alipay_account, $account_holder, $bank_name, 
        $bank_card_number, $wechat_nickname, $status, $is_admin, $userId
    ])) {
        echo json_encode(['success' => true, 'message' => '用户信息更新成功']);
    } else {
        echo json_encode(['success' => false, 'message' => '用户信息更新失败']);
    }
} else {
    echo json_encode(['success' => false, 'message' => '无效的请求方法']);
}
?>